var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var isPosting = false;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: 'artartimages',
  operator: 'upyunadmin2014',
  getSignatureUrl: 'https://api.artart.cn/api.php?ac=signupyun&publickey=' + util.publiccode
});
var oldData = '';
var isEdit = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    minHeight: 0,
    classlysData: [],
    typeIndex: 0,
    selClassly: {},
    uploadImg: [],
    token: "",
    uid: 0,
    imgWH: 0,
    titleValue: '',
    message: '',
    date: '',
    startDate: '',
    endDate: '',
    show_addClass_view:false,
    className:'',
    show_edit_view: false,
    chang:'',
    kuan: '',
    gao: '',
    lwh_size:'',
    caizhiValue: '',
    focus:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    oldData = '';
    isEdit = false;
    var that = this;
    if (options.data) {//有数据传过来，说明是编
      wx.showLoading({
        title: '加载中',
      })
      oldData = JSON.parse(options.data);
      isEdit = true;
      console.log("要编辑的数据：", oldData);
    }
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token
        });
        that.loadClasslyData();
      }
    });

    var curDate = new Date();
    var curYear = curDate.getFullYear();
    var curDate_f = util.formatTime(curDate, '-', '');
    var startDate_f = util.formatTime(new Date(curYear - 50, 0, 1), '-', '');
    var endDate_f = util.formatTime(new Date(curYear + 49, 11, 31), '-', '');
    console.log("curDate_f = " + curDate_f + "; startDate_f = " + startDate_f + "; endDate_f = " + endDate_f);
    this.setData({
      date: curDate_f,
      startDate: startDate_f,
      endDate: endDate_f
    });
    this.load();
    
  },
  load: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight - 40,
          imgWH: (res.windowWidth - 18) / 4 - 12
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (isEdit) {
      var size = '';
      if (oldData.width) {
        size = oldData.width;
      }
      if (oldData.height) {
        if (size) {
          size += ('×' + oldData.height);
        } else {
          size = oldData.height;
        }
      }
      if (oldData.long) {
        if (size) {
          size += ('×' + oldData.long);
        } else {
          size = oldData.long;
        }
      }
      if (size) {
        size += 'cm';
      }
      var photoArray = [];
      if (oldData.photos) {
        photoArray = oldData.photos.split(',');
      }
      var selClassly = { name: oldData.arttype, id: oldData.albumid };
      this.setData({
        titleValue: oldData.topictitle,
        selClassly: selClassly,
        date: oldData.age,
        lwh_size: size,
        caizhiValue: oldData.caizhi,
        uploadImg: photoArray,
        message: oldData.message,
        kuan: oldData.width,
        chang: oldData.height,
        gao: oldData.long,
      });
      wx.hideLoading();
    }
    
  },

  textAreaEdited_title: function (e) {
    var value = e.detail.value;
    console.log("title: " + value);
    this.setData({
      titleValue: value
    });
  },

  addClassAction:function(){
    var className = this.data.className;
    if (!className || className == '中文|English'){
      app.dialog("请输入分类名", 'loading');
      return;
    }
    // if(className.indexOf('|') <= 0 || className.indexOf('|') == className.length - 1){
    //   app.dialog("请使用 '|' 分隔中、英文名", 'loading');
    //   return;
    // }
    this.addClassly();
  },

  okAction: function (e) {
    var size ='';
    
    if (this.data.kuan){
      size = this.data.kuan;
    }
    if (this.data.chang){
      if(size) {
        size += ('×' + this.data.chang);
      } else {
        size = this.data.chang;
      }
    }
    if (this.data.gao){
      if (size) {
        size += ('×' + this.data.gao);
      } else {
        size = this.data.gao;
      }
    }
    if (size){
      size += 'cm';
    }
    
    this.setData({
      show_edit_view: false,
      focus:false,
      lwh_size: size,
    });
  },

  editAction: function (e) {
    this.setData({
      show_edit_view: true,
      focus: true,
    });
  },

  hiddenEditView: function () {
    this.setData({
      show_edit_view: false,
      focus: false,
      show_addClass_view: false,
    });
  },

  sizeEdit:function(e){
    var name = e.currentTarget.dataset.name;
    console.log("name = " + name);
    if(name == 'chang'){
      this.setData({
        chang: e.detail.value
      })
    } else if (name == 'kuan') {
      this.setData({
        kuan: e.detail.value
      })
    } else if (name == 'gao') {
      this.setData({
        gao: e.detail.value
      })
    } else if (name == 'class') {
      this.setData({
        className: e.detail.value
      })
    }
  },


  bindDateDate: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  releaseSubmit: function (e) {
    if (isPosting) {
      return false;
    }
    isPosting = true;

    //图片
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var photos_param = "";
    if (photos.length == 0) {
        app.dialog('请添加作品图', 'loading');
        isPosting = false;
        return false;
    } else {
      //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.imgHost + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');
    }

    // var title = this.data.titleValue;//标题
    var title = e.detail.value.title;
    if (!title || title.trim().length <= 0) {
      app.dialog('请输入名称', 'loading');
      isPosting = false;
      return false;
    }
    var classlyData = this.data.selClassly;//分类
    if (!classlyData || !classlyData.id) {
      app.dialog('请选择分类', 'loading');
      isPosting = false;
      return false;
    }

    // wx.showLoading({ title: '发布中，请稍等' });
    wx.showLoading({ title: '发布中...' });
    var date = this.data.date;
    var caizhi = e.detail.value.caizhi;
    var message = e.detail.value.message;
    
    var action = "posttopic";
    if (isEdit) {
      action = "edittopic";
    }
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + action + token);//私钥
    var data = {
      ac: action,
      topictype: 6,
      privatekey: privatekey,
      uid: uid,
      postuid: uid,
      topictitle: title,
      width: this.data.kuan,
      height: this.data.chang,
      long: this.data.gao,
      albumid: classlyData.id,
      arttype: classlyData.name,
      caizhi: caizhi,
      age: date,
      message: message,
      xcx: 1,
      photos: photos_param
    }
    if (isEdit) {
      data.topicid = oldData.id;
    }
    console.log("作品：", data);
    
    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        wx.hideLoading();
        if (responseData.data.id) {//你看是不是这个字段判断发布失败还是成功的
          isPosting = false;
          // wx.redirectTo({ url: "/pages/index/index?go=dongtai" });
          wx.reLaunch({ url: "/pages/index/index?go=dongtai" });
        } else {
          app.dialog('发布失败', 'loading');
          isPosting = false;
        }

      },
      fail: function (e) {
        isPosting = false;
        wx.hideLoading();
      }
    });
  },
  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({ title: '图片上传中..', mask:'true'});
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  //作品类型选择
  bindPickerSelType: function (e) {
    var index = e.detail.value;
    var selClassLy = this.data.classlysData[index];
    if(selClassLy.id == -1) {
      this.setData({
        show_addClass_view:true
      })
    } else {
      var that = this;
      this.setData({
        typeIndex: index,
        selClassly: that.data.classlysData[index]
      })
    }
  },

  loadClasslyData: function () {
    var that = this;
    var uid = this.data.uid;
    var params = '';
    var actionItem = '';
      params = {
        ac: "getalbum",
        publickey: util.publiccode,
        uid: uid,
        type: 1
      }
      console.log("getalbum params: ", params);
    util.api({
      
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("作品类别：", result);
        if (result.msg) {
          var addData = [{
            name: "新增分类",
            id:-1
          }];
          that.setData({
            classlysData: addData,
          });
        } else {
          that.setData({
            classlysData: result
          });
        }

      }
    });
  },

  addClassly:function(){
    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'addalbum' + token);//私钥

    var params = {
      ac: "addalbum",
      privatekey: privatekey,
      name:that.data.className,
      uid: uid,
      type: 1
    }
    console.log("addalbum params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("add作品类别：", result);
        if (result.msg) {
          
        } else {
          that.setData({
            classlysData: result,
            show_addClass_view:false,
            selClassly: result[0]
          });
        }

      }
    })
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // }
})